package week7.day43;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author fengzihao
 * @Date 2024-05-27 20:21
 */
public class Request {
    // 请求报文
    private String requestMessage;

    // 定义几个成员变量用来接收请求方法、请求资源、版本协议
    private String method;

    private String uri;

    private String protocol;

    private Map<String, String> headerMap = new HashMap<>();

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public Request(Socket client) {
        InputStream inputStream = null;
        try {
            inputStream = client.getInputStream();
            byte[] bytes = new byte[1024];
            int length = inputStream.read(bytes);
            this.requestMessage = new String(bytes, 0, length);
            parseRequestLine();
            parserRequestHeader();
            // 请求体我们不处理
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 此时，尝试去接收客户端传递过来的请求信息

    }

    // 解析请求头
    private void parserRequestHeader() {
        String[] split = this.requestMessage.split("\r\n\r\n");
        String string = split[0];
        String[] split1 = string.split("\r\n");
        for (int i = 0; i < split1.length; i++) {
            if (i == 0)
                continue;
            String[] strings = split1[i].split(": ");
            // System.out.println("strings = " + strings[0] + "   " + strings[1]);
            headerMap.put(strings[0], strings[1]);
        }
    }

    // 解析请求行，找到请求行开始(0)、结束(\r\n下标)的位置
    private void parseRequestLine() {
        int index = this.requestMessage.indexOf("\r\n");
        String line = requestMessage.substring(0, index);
        String[] parts = line.split(" ");
        this.method = parts[0];
        this.uri = parts[1];
        this.protocol = parts[2];
    }

    // 补全代码
    public String getHeader(String header) {
        return headerMap.get(header);
    }

    public Set<String> getHeaderNames() {
        Set<String> strings = headerMap.keySet();
        for (String string : strings) {
            System.out.println("string = " + string);
        }
        return headerMap.keySet();
    }
}
